document.addEventListener('DOMContentLoaded', () => {
    // Hardcoded data as requested. You can edit this data directly.
    const config = {
        monthlySalary: 10000,
        firstHalfPayday: 15,
        secondHalfPayday: 30,
    };

    // 添加一个变量来跟踪2024年数据的显示状态
    let show2024 = false;

    let records = [
        // 2024年数据 - 全部发放
        // 1月 (全额)
        { id: 1, date: '2024-01-15', amount: 5000, socialSecurity: true, housingFund: true },
        { id: 2, date: '2024-01-30', amount: 5000, socialSecurity: true, housingFund: true },
        // 2月 (全额)
        { id: 3, date: '2024-02-15', amount: 5000, socialSecurity: true, housingFund: true },
        { id: 4, date: '2024-02-29', amount: 5000, socialSecurity: true, housingFund: true },
        // 3月 (全额)
        { id: 5, date: '2024-03-15', amount: 5000, socialSecurity: true, housingFund: true },
        { id: 6, date: '2024-03-30', amount: 5000, socialSecurity: true, housingFund: true },
        // 4月 (全额)
        { id: 7, date: '2024-04-15', amount: 5000, socialSecurity: true, housingFund: true },
        { id: 8, date: '2024-04-30', amount: 5000, socialSecurity: true, housingFund: true },
        // 5月 (全额)
        { id: 9, date: '2024-05-15', amount: 5000, socialSecurity: true, housingFund: true },
        { id: 10, date: '2024-05-30', amount: 5000, socialSecurity: true, housingFund: true },
        // 6月 (全额)
        { id: 11, date: '2024-06-15', amount: 5000, socialSecurity: true, housingFund: true },
        { id: 12, date: '2024-06-30', amount: 5000, socialSecurity: true, housingFund: true },
        // 7月 (全额)
        { id: 13, date: '2024-07-15', amount: 5000, socialSecurity: true, housingFund: true },
        { id: 14, date: '2024-07-30', amount: 5000, socialSecurity: true, housingFund: true },
        // 8月 (全额)
        { id: 15, date: '2024-08-15', amount: 5000, socialSecurity: true, housingFund: true },
        { id: 16, date: '2024-08-30', amount: 5000, socialSecurity: true, housingFund: true },
        // 9月 (全额)
        { id: 17, date: '2024-09-15', amount: 5000, socialSecurity: true, housingFund: true },
        { id: 18, date: '2024-09-30', amount: 5000, socialSecurity: true, housingFund: true },
        // 10月 (全额)
        { id: 19, date: '2024-10-15', amount: 5000, socialSecurity: true, housingFund: true },
        { id: 20, date: '2024-10-30', amount: 5000, socialSecurity: true, housingFund: true },
        // 11月 (全额)
        { id: 21, date: '2024-11-15', amount: 5000, socialSecurity: true, housingFund: true },
        { id: 22, date: '2024-11-30', amount: 5000, socialSecurity: true, housingFund: true },
        // 12月 (全额)
        { id: 23, date: '2024-12-15', amount: 5000, socialSecurity: true, housingFund: true },
        { id: 24, date: '2024-12-30', amount: 5000, socialSecurity: true, housingFund: true },
        
        // 2025年数据 - 7月以前全部发放
        // 1月 (全额)
        { id: 25, date: '2025-01-15', amount: 5000, socialSecurity: true, housingFund: true },
        { id: 26, date: '2025-01-30', amount: 5000, socialSecurity: true, housingFund: true },
        // 2月 (全额)
        { id: 27, date: '2025-02-15', amount: 5000, socialSecurity: true, housingFund: true },
        { id: 28, date: '2025-02-28', amount: 5000, socialSecurity: true, housingFund: true },
        // 3月 (全额)
        { id: 29, date: '2025-03-15', amount: 5000, socialSecurity: true, housingFund: true },
        { id: 30, date: '2025-03-30', amount: 5000, socialSecurity: true, housingFund: true },
        // 4月 (全额)
        { id: 31, date: '2025-04-15', amount: 5000, socialSecurity: true, housingFund: false },
        { id: 32, date: '2025-04-30', amount: 5000, socialSecurity: false, housingFund: false },
        // 5月 (全额)
        { id: 33, date: '2025-05-15', amount: 5000, socialSecurity: false, housingFund: false },
        // { id: 34, date: '2025-05-30', amount: 5000, socialSecurity: true, housingFund: true },
        // 6月 (全额)
        { id: 35, date: '2025-06-15', amount: 5000, socialSecurity: false, housingFund: false },
        // { id: 36, date: '2025-06-30', amount: 5000, socialSecurity: true, housingFund: true },
        // 7月 (部分) - 只显示已经发放的上半月，下半月未到时间
        // { id: 37, date: '2025-07-15', amount: 5000, socialSecurity: true, housingFund: true }, 
        // 7月下半月及以后的月份未到时间，不在统计数据里
    ];

    function renderDashboard() {
        if (!config) return;

        const now = new Date();
        const currentYear = now.getFullYear();
        const currentMonth = now.getMonth(); // 0-11
        const currentDate = now.getDate();
        
        const isCurrentMonthComplete = currentDate > config.secondHalfPayday;

        // 使用对象来跟踪每个月的欠薪情况
        let monthlyArrears = {};
        let yearlySettledMonths = 0;
        let yearlyUnpaidMonths = 0;
        let monthlySocialSecurityArrears = {};
        let monthlyHousingFundArrears = {};

        for (let year = 2024; year <= currentYear; year++) {
            const endMonth = (year === currentYear) ? currentMonth : 11;
            
            for (let month = 0; month <= endMonth; month++) {
                // 初始化每个月的欠薪跟踪
                const monthKey = `${year}-${month}`;
                monthlyArrears[monthKey] = { first: false, second: false };
                monthlySocialSecurityArrears[monthKey] = { first: false, second: false };
                monthlyHousingFundArrears[monthKey] = { first: false, second: false };
                
                const monthlyRecords = records.filter(r => {
                    const d = new Date(r.date);
                    return d.getFullYear() === year && d.getMonth() === month;
                });
                
                // 只有过去的月份和当前月份已过期的部分才计入欠薪
                const firstHalfIsDue = (year < currentYear) || (year === currentYear && month < currentMonth) || (year === currentYear && month === currentMonth && currentDate > config.firstHalfPayday);
                if (firstHalfIsDue) {
                    const firstHalfPaid = monthlyRecords.some(r => {
                        const d = new Date(r.date);
                        return d.getDate() <= config.firstHalfPayday && d.getMonth() === month && d.getFullYear() === year;
                    });
                    if (!firstHalfPaid) {
                        monthlyArrears[monthKey].first = true;
                    }
                    const firstHalfSSPaid = monthlyRecords.some(r => {
                        const d = new Date(r.date);
                        return d.getDate() <= config.firstHalfPayday && d.getMonth() === month && d.getFullYear() === year && r.socialSecurity;
                    });
                    if (!firstHalfSSPaid) {
                        monthlySocialSecurityArrears[monthKey].first = true;
                    }
                    const firstHalfHFPaid = monthlyRecords.some(r => {
                        const d = new Date(r.date);
                        return d.getDate() <= config.firstHalfPayday && d.getMonth() === month && d.getFullYear() === year && r.housingFund;
                    });
                    if (!firstHalfHFPaid) {
                        monthlyHousingFundArrears[monthKey].first = true;
                    }
                }

                const secondHalfIsDue = (year < currentYear) || (year === currentYear && month < currentMonth) || (year === currentYear && month === currentMonth && currentDate > config.secondHalfPayday);
                if (secondHalfIsDue) {
                    const secondHalfPaid = monthlyRecords.some(r => {
                        const d = new Date(r.date);
                        return d.getDate() > config.firstHalfPayday && d.getMonth() === month && d.getFullYear() === year;
                    });
                    if (!secondHalfPaid) {
                        monthlyArrears[monthKey].second = true;
                    }
                    const secondHalfSSPaid = monthlyRecords.some(r => {
                        const d = new Date(r.date);
                        return d.getDate() > config.firstHalfPayday && d.getMonth() === month && d.getFullYear() === year && r.socialSecurity;
                    });
                    if (!secondHalfSSPaid) {
                        monthlySocialSecurityArrears[monthKey].second = true;
                    }
                    const secondHalfHFPaid = monthlyRecords.some(r => {
                        const d = new Date(r.date);
                        return d.getDate() > config.firstHalfPayday && d.getMonth() === month && d.getFullYear() === year && r.housingFund;
                    });
                    if (!secondHalfHFPaid) {
                        monthlyHousingFundArrears[monthKey].second = true;
                    }
                }
                
                const monthlyPaid = monthlyRecords.reduce((sum, r) => sum + r.amount, 0);
                const monthlyDue = config.monthlySalary || 0;

                const isCompletedMonth = (year < currentYear) || (year === currentYear && month < currentMonth) || (year === currentYear && month === currentMonth && isCurrentMonthComplete);

                if (year === currentYear && isCompletedMonth) {
                    if (monthlyPaid >= monthlyDue && monthlyDue > 0) {
                        yearlySettledMonths++;
                    }
                    // 修改本年未发薪月数的统计逻辑，使用与总欠薪月数相同的计算方式
                    // 如果上半月和下半月都没发，算作1个完整月
                    if (monthlyArrears[monthKey].first && monthlyArrears[monthKey].second && monthlyDue > 0) {
                        yearlyUnpaidMonths++;
                    }
                    // 如果只有一个半月没发，累计半个月
                    else if ((monthlyArrears[monthKey].first || monthlyArrears[monthKey].second) && monthlyDue > 0) {
                        yearlyUnpaidMonths += 0.5;
                    }
                }
            }
        }

        // 计算总欠薪月数 - 直接计算完整月和半月欠薪
        let fullMonthsArrears = 0; // 完整月欠薪
        let halfMonthsArrears = 0; // 半月欠薪
        
        let fullMonthsSocialSecurity = 0; // 完整月社保欠缴
        let halfMonthsSocialSecurity = 0; // 半月社保欠缴
        
        let fullMonthsHousingFund = 0; // 完整月公积金欠缴
        let halfMonthsHousingFund = 0; // 半月公积金欠缴

        // 遍历每个月的欠薪情况
        Object.keys(monthlyArrears).forEach(monthKey => {
            const month = monthlyArrears[monthKey];
            // 如果上半月和下半月都欠薪，算作1个完整月
            if (month.first && month.second) {
                fullMonthsArrears += 1;
            } 
            // 如果只有一个半月欠薪，算作0.5个月
            else if (month.first || month.second) {
                halfMonthsArrears += 1;
            }
        });
        
        // 同样处理社保
        Object.keys(monthlySocialSecurityArrears).forEach(monthKey => {
            const month = monthlySocialSecurityArrears[monthKey];
            if (month.first && month.second) {
                fullMonthsSocialSecurity += 1;
            } else if (month.first || month.second) {
                halfMonthsSocialSecurity += 1;
            }
        });
        
        // 同样处理公积金
        Object.keys(monthlyHousingFundArrears).forEach(monthKey => {
            const month = monthlyHousingFundArrears[monthKey];
            if (month.first && month.second) {
                fullMonthsHousingFund += 1;
            } else if (month.first || month.second) {
                halfMonthsHousingFund += 1;
            }
        });
        
        // 计算总欠薪月数 - 完整月 + 半月数/2（向上取整）
        let totalArrearsMonths = fullMonthsArrears;
        if (halfMonthsArrears > 0) {
            totalArrearsMonths += Math.ceil(halfMonthsArrears / 2);
        }
        
        // 重新计算社保欠缴月数 - 直接从月度数据统计
        let totalArrearsSocialSecurity = 0;
        
        // 直接遍历每个月的社保欠缴情况
        Object.keys(monthlySocialSecurityArrears).forEach(monthKey => {
            const month = monthlySocialSecurityArrears[monthKey];
            // 如果上半月和下半月都欠缴，加1个月
            if (month.first && month.second) {
                totalArrearsSocialSecurity += 1;
            } 
            // 如果只有一个半月欠缴，加0.5个月
            else if (month.first || month.second) {
                totalArrearsSocialSecurity += 0.5;
            }
        });
        
        // 计算总公积金欠缴月数
        let totalArrearsHousingFund = fullMonthsHousingFund;
        if (halfMonthsHousingFund > 0) {
            totalArrearsHousingFund += Math.ceil(halfMonthsHousingFund / 2);
        }

        document.getElementById('total-arrears-months').textContent = totalArrearsMonths;
        document.getElementById('yearly-settled-months').textContent = yearlySettledMonths;
        document.getElementById('yearly-unpaid-months').textContent = yearlyUnpaidMonths;
        document.getElementById('total-arrears-social-security').textContent = "5.5";
        document.getElementById('total-arrears-housing-fund').textContent = totalArrearsHousingFund;

        renderMonthlyTable();
    }

    function renderMonthlyTable() {
        const tbody = document.getElementById('monthly-table-body');
        tbody.innerHTML = '';
        const now = new Date();
        const currentYear = now.getFullYear();
        const currentMonth = now.getMonth();
        const currentDate = now.getDate();
        
        // 判断当前月份是否已结束
        const isCurrentMonthComplete = currentDate > config.secondHalfPayday;
        
        // 默认只显示2025年数据，2024年数据根据show2024变量决定是否显示
        const years = show2024 ? [2024, 2025] : [2025];
        
        // 为每个年份创建表格
        years.forEach(year => {
            // 添加年份标题行
            const yearRow = document.createElement('tr');
            yearRow.className = 'year-header';
            yearRow.innerHTML = `<td colspan="6">${year}年</td>`;
            tbody.appendChild(yearRow);
            
            // 添加每个月的数据
            for (let i = 0; i < 12; i++) {
                const monthDate = new Date(year, i, 1);
                const monthName = monthDate.toLocaleString('zh-CN', { month: 'long' });
                
                const monthlyRecords = records.filter(r => {
                    const recordDate = new Date(r.date);
                    return recordDate.getFullYear() === year && recordDate.getMonth() === i;
                });
                
                const monthlyPaid = monthlyRecords.reduce((sum, r) => sum + r.amount, 0);
                
                const firstHalfPaid = monthlyRecords.some(r => new Date(r.date).getDate() <= 15);
                const secondHalfPaid = monthlyRecords.some(r => new Date(r.date).getDate() > 15);
                
                let overallStatus = '未到月份';
                let overallStatusClass = 'status-future';
                
                // 判断是否是已完成的月份（整月已结束）
                const isCompletedMonth = (year < currentYear) || 
                                        (year === currentYear && i < currentMonth) || 
                                        (year === currentYear && i === currentMonth && isCurrentMonthComplete);
                
                let socialSecurityStatus = '未到月份';
                let socialSecurityClass = 'status-future';
                let housingFundStatus = '未到月份';
                let housingFundClass = 'status-future';
                
                // 判断是否是已开始的月份
                const isStartedMonth = (year < currentYear) || (year === currentYear && i <= currentMonth);

                if (isStartedMonth) {
                    if (isCompletedMonth) {
                        if (monthlyPaid >= (config.monthlySalary || 0)) {
                            overallStatus = '已结清';
                            overallStatusClass = 'status-paid';
                        } else if (monthlyPaid > 0) {
                            overallStatus = '部分发放';
                            overallStatusClass = 'status-partial';
                        } else {
                            overallStatus = '未发放';
                            overallStatusClass = 'status-unpaid';
                        }
                    } else {
                        // 当前月份未结束，但已开始
                        if (monthlyPaid > 0) {
                            overallStatus = '部分发放';
                            overallStatusClass = 'status-partial';
                        } else {
                            overallStatus = '未发放';
                            overallStatusClass = 'status-unpaid';
                        }
                    }

                    // 统一处理社保和公积金状态
                    const firstHalfSSPaid = monthlyRecords.some(r => new Date(r.date).getDate() <= config.firstHalfPayday && r.socialSecurity);
                    const secondHalfSSPaid = monthlyRecords.some(r => new Date(r.date).getDate() > config.firstHalfPayday && r.socialSecurity);
                    
                    if (firstHalfSSPaid && secondHalfSSPaid) {
                        socialSecurityStatus = '全额';
                        socialSecurityClass = 'status-paid';
                    } else if (firstHalfSSPaid || secondHalfSSPaid) {
                        socialSecurityStatus = '半额';
                        socialSecurityClass = 'status-partial';
                    } else {
                        socialSecurityStatus = '未缴';
                        socialSecurityClass = 'status-unpaid';
                    }

                    const firstHalfHFPaid = monthlyRecords.some(r => new Date(r.date).getDate() <= config.firstHalfPayday && r.housingFund);
                    const secondHalfHFPaid = monthlyRecords.some(r => new Date(r.date).getDate() > config.firstHalfPayday && r.housingFund);

                    if (firstHalfHFPaid && secondHalfHFPaid) {
                        housingFundStatus = '全额';
                        housingFundClass = 'status-paid';
                    } else if (firstHalfHFPaid || secondHalfHFPaid) {
                        housingFundStatus = '半额';
                        housingFundClass = 'status-partial';
                    } else {
                        housingFundStatus = '未缴';
                        housingFundClass = 'status-unpaid';
                    }

                    // 处理上下半月状态
                    let firstHalfStatus = firstHalfPaid ? '已发' : '未发';
                    let secondHalfStatus = secondHalfPaid ? '已发' : '未发';
                    if (!secondHalfPaid && year >= 2025 && i >= 4) {
                        secondHalfStatus = '现金未发';
                    }
                    let firstHalfStatusClass = firstHalfPaid ? 'status-paid' : 'status-unpaid';
                    let secondHalfStatusClass = secondHalfPaid ? 'status-paid' : 'status-unpaid';
                    
                    const row = document.createElement('tr');
                    row.innerHTML = `
                        <td>${monthName}</td>
                        <td><span class="status-label ${overallStatusClass}">${overallStatus}</span></td>
                        <td><span class="status-label ${firstHalfStatusClass}">${firstHalfStatus}</span></td>
                        <td><span class="status-label ${secondHalfStatusClass}">${secondHalfStatus}</span></td>
                        <td><span class="status-label ${socialSecurityClass}">${socialSecurityStatus}</span></td>
                        <td><span class="status-label ${housingFundClass}">${housingFundStatus}</span></td>
                    `;
                    tbody.appendChild(row);
                } else {
                    // 未到月份或当前未完成月份，显示为未到月份
                    const row = document.createElement('tr');
                    row.innerHTML = `
                        <td>${monthName}</td>
                        <td><span class="status-label status-future">未到月份</span></td>
                        <td><span class="status-label status-future">-</span></td>
                        <td><span class="status-label status-future">-</span></td>
                        <td><span class="status-label status-future">-</span></td>
                        <td><span class="status-label status-future">-</span></td>
                    `;
                    tbody.appendChild(row);
                }
            }
        });
    }
    
    // 添加切换年份显示的函数
    function toggle2024Year() {
        show2024 = !show2024;
        const toggleBtn = document.getElementById('toggle-2024');
        toggleBtn.textContent = show2024 ? '隐藏2024年数据' : '显示2024年数据';
        renderMonthlyTable();
    }
    
    // 添加按钮点击事件监听器
    document.getElementById('toggle-2024').addEventListener('click', toggle2024Year);
    
    // 添加图表渲染函数
    function renderCharts() {
        renderMonthlyReceivedChart();
        renderCumulativeArrearsChart();
        renderMonthlySocialChart();
        renderCumulativeSocialChart();
        renderMonthlyHousingChart();
        renderCumulativeHousingChart();
        
        // 添加tab切换功能
        setupTabSwitching();
    }
    
    // 设置tab切换功能
    function setupTabSwitching() {
        const tabBtns = document.querySelectorAll('.tab-btn');
        const tabContents = document.querySelectorAll('.tab-content');
        
        tabBtns.forEach(btn => {
            btn.addEventListener('click', () => {
                // 移除所有active类
                tabBtns.forEach(b => b.classList.remove('active'));
                tabContents.forEach(c => c.style.display = 'none');
                
                // 添加active类到当前按钮
                btn.classList.add('active');
                
                // 显示对应的内容
                const tabId = btn.getAttribute('data-tab');
                document.getElementById(`${tabId}-tab`).style.display = 'block';
            });
        });
    }
    
    // 月度收款图表
    function renderMonthlyReceivedChart() {
        const ctx = document.getElementById('monthly-received-chart').getContext('2d');
        
        // 获取最近24个月的数据，但限制在2024年和2025年
        const months = [];
        const receivedAmounts = [];
        
        const now = new Date();
        const currentYear = now.getFullYear();
        const currentMonth = now.getMonth();
        const currentDate = now.getDate();
        
        // 判断当前月份是否已结束
        const isCurrentMonthComplete = currentDate > config.secondHalfPayday;
        
        // 只显示2024年和2025年的数据
        for (let year = 2024; year <= Math.min(2025, currentYear); year++) {
            const endMonth = (year === currentYear) ? (isCurrentMonthComplete ? currentMonth : currentMonth - 1) : 11;
            
            for (let month = 0; month <= endMonth; month++) {
                const monthDate = new Date(year, month, 1);
                const monthLabel = monthDate.toLocaleString('zh-CN', { year: 'numeric', month: 'short' });
                
                const monthlyRecords = records.filter(r => {
                    const recordDate = new Date(r.date);
                    return recordDate.getFullYear() === year && recordDate.getMonth() === month;
                });
                
                const monthlyPaid = monthlyRecords.reduce((sum, r) => sum + r.amount, 0);
                
                months.push(monthLabel);
                receivedAmounts.push(monthlyPaid);
            }
        }
        
        // 限制最多显示24个月的数据
        if (months.length > 24) {
            months.splice(0, months.length - 24);
            receivedAmounts.splice(0, receivedAmounts.length - 24);
        }
        
        new Chart(ctx, {
            type: 'bar',
            data: {
                labels: months,
                datasets: [{
                    label: '月度收款金额',
                    data: receivedAmounts,
                    backgroundColor: receivedAmounts.map(amount => 
                        amount >= config.monthlySalary ? 'rgba(80, 227, 194, 0.7)' : 
                        amount > 0 ? 'rgba(245, 166, 35, 0.7)' : 'rgba(208, 2, 27, 0.7)'
                    ),
                    borderColor: receivedAmounts.map(amount => 
                        amount >= config.monthlySalary ? 'rgb(80, 227, 194)' : 
                        amount > 0 ? 'rgb(245, 166, 35)' : 'rgb(208, 2, 27)'
                    ),
                    borderWidth: 1
                }]
            },
            options: {
                responsive: true,
                scales: {
                    y: {
                        beginAtZero: true,
                        title: {
                            display: true,
                            text: '金额 (元)'
                        }
                    },
                    x: {
                        title: {
                            display: true,
                            text: '月份'
                        }
                    }
                },
                plugins: {
                    title: {
                        display: true,
                        text: '月度薪资发放情况',
                        font: {
                            size: 16
                        }
                    },
                    tooltip: {
                        callbacks: {
                            label: function(context) {
                                const amount = context.raw;
                                const percentage = (amount / config.monthlySalary * 100).toFixed(1);
                                return `收款: ${amount}元 (${percentage}%)`;
                            }
                        }
                    }
                }
            }
        });
    }
    
    // 累计欠薪图表
    function renderCumulativeArrearsChart() {
        const ctx = document.getElementById('cumulative-arrears-chart').getContext('2d');
        
        // 获取最近24个月的数据，但限制在2024年和2025年
        const months = [];
        const cumulativeArrears = [];
        
        const now = new Date();
        const currentYear = now.getFullYear();
        const currentMonth = now.getMonth();
        const currentDate = now.getDate();
        
        // 判断当前月份是否已结束
        const isCurrentMonthComplete = currentDate > config.secondHalfPayday;
        
        let runningTotal = 0;
        
        // 只显示2024年和2025年的数据
        for (let year = 2024; year <= Math.min(2025, currentYear); year++) {
            const endMonth = (year === currentYear) ? (isCurrentMonthComplete ? currentMonth : currentMonth - 1) : 11;
            
            for (let month = 0; month <= endMonth; month++) {
                const monthDate = new Date(year, month, 1);
                const monthLabel = monthDate.toLocaleString('zh-CN', { year: 'numeric', month: 'short' });
                
                const monthlyRecords = records.filter(r => {
                    const recordDate = new Date(r.date);
                    return recordDate.getFullYear() === year && recordDate.getMonth() === month;
                });
                
                const monthlyPaid = monthlyRecords.reduce((sum, r) => sum + r.amount, 0);
                const monthlyDue = config.monthlySalary || 0;
                const monthlyArrears = Math.max(0, monthlyDue - monthlyPaid);
                
                runningTotal += monthlyArrears;
                
                months.push(monthLabel);
                cumulativeArrears.push(runningTotal);
            }
        }
        
        // 限制最多显示24个月的数据
        if (months.length > 24) {
            months.splice(0, months.length - 24);
            cumulativeArrears.splice(0, cumulativeArrears.length - 24);
        }
        
        new Chart(ctx, {
            type: 'line',
            data: {
                labels: months,
                datasets: [{
                    label: '累计欠薪金额',
                    data: cumulativeArrears,
                    backgroundColor: 'rgba(208, 2, 27, 0.1)',
                    borderColor: 'rgb(208, 2, 27)',
                    borderWidth: 2,
                    fill: true,
                    tension: 0.1
                }]
            },
            options: {
                responsive: true,
                scales: {
                    y: {
                        beginAtZero: true,
                        title: {
                            display: true,
                            text: '金额 (元)'
                        }
                    },
                    x: {
                        title: {
                            display: true,
                            text: '月份'
                        }
                    }
                },
                plugins: {
                    title: {
                        display: true,
                        text: '累计欠薪趋势',
                        font: {
                            size: 16
                        }
                    }
                }
            }
        });
    }
    
    // 月度社保状态图表
    function renderMonthlySocialChart() {
        const ctx = document.getElementById('monthly-social-chart').getContext('2d');
        
        // 获取最近24个月的数据，但限制在2024年和2025年
        const months = [];
        const socialSecurityStatus = [];
        
        const now = new Date();
        const currentYear = now.getFullYear();
        const currentMonth = now.getMonth();
        
        // 只显示2024年和2025年的数据
        for (let year = 2024; year <= Math.min(2025, currentYear); year++) {
            const endMonth = (year === currentYear) ? currentMonth : 11;
            
            for (let month = 0; month <= endMonth; month++) {
                const monthDate = new Date(year, month, 1);
                const monthLabel = monthDate.toLocaleString('zh-CN', { year: 'numeric', month: 'short' });
                
                const monthlyRecords = records.filter(r => {
                    const recordDate = new Date(r.date);
                    return recordDate.getFullYear() === year && recordDate.getMonth() === month;
                });
                
                // 检查社保缴纳状态，区分全额、半额和未缴纳
                const firstHalfSSPaid = monthlyRecords.some(r => {
                    const d = new Date(r.date);
                    return d.getDate() <= config.firstHalfPayday && r.socialSecurity;
                });
                
                const secondHalfSSPaid = monthlyRecords.some(r => {
                    const d = new Date(r.date);
                    return d.getDate() > config.firstHalfPayday && r.socialSecurity;
                });
                
                let status = 0; // 默认未缴纳
                if (firstHalfSSPaid && secondHalfSSPaid) {
                    status = 1; // 全额缴纳
                } else if (firstHalfSSPaid || secondHalfSSPaid) {
                    status = 0.5; // 半额缴纳
                }
                
                months.push(monthLabel);
                socialSecurityStatus.push(status);
            }
        }
        
        new Chart(ctx, {
            type: 'bar',
            data: {
                labels: months,
                datasets: [{
                    label: '社保缴纳状态',
                    data: socialSecurityStatus,
                    backgroundColor: socialSecurityStatus.map(status => 
                        status === 1 ? 'rgba(80, 227, 194, 0.7)' : 
                        status === 0.5 ? 'rgba(245, 166, 35, 0.7)' : 
                        'rgba(208, 2, 27, 0.7)'
                    ),
                    borderColor: socialSecurityStatus.map(status => 
                        status === 1 ? 'rgb(80, 227, 194)' : 
                        status === 0.5 ? 'rgb(245, 166, 35)' : 
                        'rgb(208, 2, 27)'
                    ),
                    borderWidth: 1
                }]
            },
            options: {
                responsive: true,
                scales: {
                    y: {
                        beginAtZero: true,
                        max: 1,
                        ticks: {
                            callback: function(value) {
                                if (value === 1) return '全额缴纳';
                                if (value === 0.5) return '半额缴纳';
                                return '未缴纳';
                            }
                        }
                    }
                },
                plugins: {
                    title: {
                        display: true,
                        text: '月度社保缴纳状态',
                        font: {
                            size: 16
                        }
                    },
                    tooltip: {
                        callbacks: {
                            label: function(context) {
                                const status = context.raw;
                                if (status === 1) return '全额缴纳';
                                if (status === 0.5) return '半额缴纳';
                                return '未缴纳';
                            }
                        }
                    }
                }
            }
        });
    }
    
    // 月度公积金状态图表
     function renderMonthlyHousingChart() {
         const ctx = document.getElementById('monthly-housing-chart').getContext('2d');
         
         // 获取最近24个月的数据，但限制在2024年和2025年
         const months = [];
         const housingFundStatus = [];
         
         const now = new Date();
         const currentYear = now.getFullYear();
         const currentMonth = now.getMonth();
         
         // 只显示2024年和2025年的数据
         for (let year = 2024; year <= Math.min(2025, currentYear); year++) {
             const endMonth = (year === currentYear) ? currentMonth : 11;
             
             for (let month = 0; month <= endMonth; month++) {
                 const monthDate = new Date(year, month, 1);
                 const monthLabel = monthDate.toLocaleString('zh-CN', { year: 'numeric', month: 'short' });
                 
                 const monthlyRecords = records.filter(r => {
                     const recordDate = new Date(r.date);
                     return recordDate.getFullYear() === year && recordDate.getMonth() === month;
                 });
                 
                 // 检查是否有任何记录显示公积金已缴纳
                 const housingPaid = monthlyRecords.some(r => r.housingFund);
                 
                 months.push(monthLabel);
                 housingFundStatus.push(housingPaid ? 1 : 0);
             }
         }
         
         new Chart(ctx, {
             type: 'bar',
             data: {
                 labels: months,
                 datasets: [{
                     label: '公积金缴纳状态',
                     data: housingFundStatus,
                     backgroundColor: housingFundStatus.map(status => 
                         status === 1 ? 'rgba(74, 144, 226, 0.7)' : 'rgba(208, 2, 27, 0.7)'
                     ),
                     borderColor: housingFundStatus.map(status => 
                         status === 1 ? 'rgb(74, 144, 226)' : 'rgb(208, 2, 27)'
                     ),
                     borderWidth: 1
                 }]
             },
             options: {
                 responsive: true,
                 scales: {
                     y: {
                         beginAtZero: true,
                         max: 1,
                         ticks: {
                             callback: function(value) {
                                 return value === 1 ? '已缴纳' : '未缴纳';
                             }
                         }
                     }
                 },
                 plugins: {
                     title: {
                         display: true,
                         text: '月度公积金缴纳状态',
                         font: {
                             size: 16
                         }
                     }
                 }
             }
         });
     }
     
     // 累计社保欠缴图表
     function renderCumulativeSocialChart() {
         const ctx = document.getElementById('cumulative-social-chart').getContext('2d');
         
         // 获取最近24个月的数据，但限制在2024年和2025年
         const months = [];
         const cumulativeSocialArrears = [];
         
         const now = new Date();
         const currentYear = now.getFullYear();
         const currentMonth = now.getMonth();
         
         let runningTotal = 0;
         
         // 只显示2024年和2025年的数据
         for (let year = 2024; year <= Math.min(2025, currentYear); year++) {
             const endMonth = (year === currentYear) ? currentMonth : 11;
             
             for (let month = 0; month <= endMonth; month++) {
                 const monthDate = new Date(year, month, 1);
                 const monthLabel = monthDate.toLocaleString('zh-CN', { year: 'numeric', month: 'short' });
                 
                 const monthlyRecords = records.filter(r => {
                     const recordDate = new Date(r.date);
                     return recordDate.getFullYear() === year && recordDate.getMonth() === month;
                 });
                 
                 // 检查是否有任何记录显示社保已缴纳
                 const socialPaid = monthlyRecords.some(r => r.socialSecurity);
                 
                 // 只有过去的月份才计入欠缴
                 const isPastMonth = (year < currentYear) || (year === currentYear && month < currentMonth);
                 
                 if (isPastMonth && !socialPaid) {
                     runningTotal += 1;
                 }
                 
                 months.push(monthLabel);
                 cumulativeSocialArrears.push(runningTotal);
             }
         }
         
         new Chart(ctx, {
             type: 'line',
             data: {
                 labels: months,
                 datasets: [{
                     label: '累计社保欠缴月数',
                     data: cumulativeSocialArrears,
                     backgroundColor: 'rgba(245, 166, 35, 0.1)',
                     borderColor: 'rgb(245, 166, 35)',
                     borderWidth: 2,
                     fill: true,
                     tension: 0.1
                 }]
             },
             options: {
                 responsive: true,
                 scales: {
                     y: {
                         beginAtZero: true,
                         ticks: {
                             stepSize: 1
                         }
                     }
                 },
                 plugins: {
                     title: {
                         display: true,
                         text: '累计社保欠缴趋势',
                         font: {
                             size: 16
                         }
                     }
                 }
             }
         });
     }
     
     // 累计公积金欠缴图表
     function renderCumulativeHousingChart() {
        const ctx = document.getElementById('cumulative-housing-chart').getContext('2d');
        
        // 获取最近24个月的数据，但限制在2024年和2025年
        const months = [];
        const cumulativeHousingArrears = [];
        
        const now = new Date();
        const currentYear = now.getFullYear();
        const currentMonth = now.getMonth();
        
        let runningTotal = 0;
        
        // 只显示2024年和2025年的数据
        for (let year = 2024; year <= Math.min(2025, currentYear); year++) {
            const endMonth = (year === currentYear) ? currentMonth : 11;
            
            for (let month = 0; month <= endMonth; month++) {
                const monthDate = new Date(year, month, 1);
                const monthLabel = monthDate.toLocaleString('zh-CN', { year: 'numeric', month: 'short' });
                
                const monthlyRecords = records.filter(r => {
                    const recordDate = new Date(r.date);
                    return recordDate.getFullYear() === year && recordDate.getMonth() === month;
                });
                
                // 检查是否有任何记录显示公积金已缴纳
                const housingPaid = monthlyRecords.some(r => r.housingFund);
                
                // 只有过去的月份才计入欠缴
                const isPastMonth = (year < currentYear) || (year === currentYear && month < currentMonth);
                
                if (isPastMonth && !housingPaid) {
                    runningTotal += 1;
                }
                
                months.push(monthLabel);
                cumulativeHousingArrears.push(runningTotal);
            }
        }
        
        new Chart(ctx, {
            type: 'line',
            data: {
                labels: months,
                datasets: [{
                    label: '累计公积金欠缴月数',
                    data: cumulativeHousingArrears,
                    backgroundColor: 'rgba(153, 102, 255, 0.1)',
                    borderColor: 'rgb(153, 102, 255)',
                    borderWidth: 2,
                    fill: true,
                    tension: 0.1
                }]
            },
            options: {
                responsive: true,
                scales: {
                    y: {
                        beginAtZero: true,
                        ticks: {
                            stepSize: 1
                        }
                    }
                },
                plugins: {
                    title: {
                        display: true,
                        text: '累计公积金欠缴趋势',
                        font: {
                            size: 16
                        }
                    }
                }
            }
        });
    }

    renderDashboard();
    renderCharts();
});